/*
 * @Author: 江舟 jijiangzhou@recycloud.cn
 * @Date: 2024-06-27 09:53:04
 * @LastEditors: 江舟 jijiangzhou@recycloud.cn
 * @LastEditTime: 2024-06-27 14:20:40
 * @FilePath: \vite-project\src\hooks\useCacheListFilter.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { useRef } from 'react';
import { useEffect, useMemo } from 'react';
import { useLocation, useParams } from 'react-router-dom-v5-compat';
import { create } from 'zustand';

type State = {
    filterMap?: {
        [path: string]: any;
    };
};
type Action = {
    updateFilterMap: (path: string, value: any) => void;
};

export const useFilterStore = create<State & Action>((set, get) => ({
    filterMap: {},
    updateFilterMap: (path: string, value: any) => {
        set((state) => ({
            filterMap: {
                ...state.filterMap,
                [path]: value,
            },
        }));
    },
}));

export const useCacheListFilter = () => {
    const formRef = useRef();
    const { filterMap, updateFilterMap } = useFilterStore();
    const location = useLocation();

    const params = useParams() || {};
    const pathname = location.pathname || '';
    let path = pathname;
    if (Object.keys(params).length) {
        for (const key in params) {
            path = path.replace(`:${key}`, params?.[key]);
        }
    }

    const filter = useMemo(() => filterMap?.[path] || {}, [filterMap, path]);

    const onSubmit = (params) => {
        // 缓存表单筛选条件
        updateFilterMap(path, {
            ...params,
            _timestamp: void 0,
        });

        return params;
    };
    const onReset = () => {
        updateFilterMap(path, {});
    };

    useEffect(() => {});

    useEffect(() => {
        if (formRef.current && filter) {
            formRef.current?.setFieldsValue(filter);
        }
    }, [formRef]);

    console.log('filter', filter, 'filterMap', filterMap, 'path', path);

    return { query: filter, formRef, onSubmit, onReset };
};
